/*
 * @Author: shimmer
 * @Date: 2022-06-14 15:54:17
 * @LastEditors: zhangzhen
 * @LastEditTime: 2022-10-20 15:38:51
 * @Description:
 *
 */
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { setLocalStorage, getLocalStorage } from '@/units/unit'

type initialStateType = {
  configs: {
    timeColor: string
    timeSize: string
    dateColor: string
    dateSize: string
    iconBorderColor: string
    iconNameColor: string
    searchWebName: {
      text: string
      value: string
    }[]
    searchValue: string
  }
  iconArr: {
    name: string
    url: string
    iconUrl: string
  }[]
  backgroundImg: string[]
  nowImg: string
}
const initialState: initialStateType = {
  configs: getLocalStorage('configs') && JSON.parse(getLocalStorage('configs'))[0],
  iconArr: getLocalStorage('iconArr') && JSON.parse(getLocalStorage('iconArr')),
  backgroundImg: getLocalStorage('backgroundImg') && JSON.parse(getLocalStorage('backgroundImg')),
  nowImg: getLocalStorage('nowImg') || '/src/assets/1659087151545.png'
}

interface PromiseNum {
  number: number
}

const promise_one: Promise<PromiseNum> = new Promise((res, rej) => {
  setTimeout(() => {
    res({ number: 10 })
  }, 3000)
})

// 异步Action
export const getAsyncInfo = createAsyncThunk('getAsyncInfo', async () => {
  const data = await promise_one
  return data
})

// 异步Action

export const stateSlice = createSlice({
  name: 'state',
  initialState,
  reducers: {
    setConfigs: (state, { payload }) => {
      state.configs = payload
      setLocalStorage('configs', [payload])
    },
    setIconArr: (state, { payload }) => {
      state.iconArr = payload
      setLocalStorage('iconArr', payload)
    },
    setNowImg: (state, { payload }) => {
      state.nowImg = payload
      setLocalStorage('nowImg', payload)
    },
    setBackgroundImg: (state, { payload }) => {
      state.backgroundImg.push(payload)
      setLocalStorage('backgroundImg', state.backgroundImg)
    },
    deleteBackgroundImg: (state, { payload }) => {
      console.log('payload: ', payload)
      const index = state.backgroundImg.findIndex((item) => item === payload)
      state.backgroundImg.splice(index, 1)
      setLocalStorage('backgroundImg', state.backgroundImg)
    }
  },
  extraReducers: (builder) => {
    // 进行请求阶段的一些操作
    builder.addCase(getAsyncInfo.pending, () => {
      console.log('进行中')
    })
    builder.addCase(getAsyncInfo.fulfilled, (state, action) => {
      console.log('action.payload: ', action.payload) //{number:"10"}
      console.log('成功')
    })
    builder.addCase(getAsyncInfo.rejected, () => {
      console.log('失败')
    })
  }
})

export const { setConfigs, setIconArr, setNowImg, setBackgroundImg, deleteBackgroundImg } = stateSlice.actions
export default stateSlice.reducer
